<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select
              v-model="q.cate_id"
              placeholder="请选择分类"
              size="small"
            >
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :label="item.cate_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="chooseClick" type="primary" size="small"
              >筛选</el-button
            >
            <el-button @click="resetList" type="info" size="small"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button
          type="primary"
          size="small"
          class="btn-pub"
          @click="pubDialogVisible = true"
          >发表文章</el-button
        >
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artList" style="width: 100%">
        <el-table-column label="文章标题">
          <template v-slot="{ row }">
            <el-link type="primary" @click="detailClick(row.id)">{{
              row.title
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="cate_name" label="分类"> </el-table-column>
        <el-table-column prop="pub_date" label="发表时间">
          <template v-slot="scope">
            {{ forMat(scope.row.pub_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态"> </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button @click="delList(row.id)" size="mini" type="danger"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 发表文章的 Dialog 对话框 -->
    <el-dialog
      title="发表文章"
      :visible.sync="pubDialogVisible"
      width="30%"
      fullscreen
      :before-close="handleClose"
      @closed="pubResetClick"
    >
      <!-- 发布文章的对话框 -->
      <el-form
        :model="pubForm"
        :rules="pubFormRules"
        ref="pubForm"
        label-width="100px"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select
            v-model="pubForm.cate_id"
            placeholder="请选择分类"
            style="width: 100%"
          >
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <quill-editor
            @change="$refs.pubForm.clearValidate('content')"
            v-model="pubForm.content"
          ></quill-editor>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img">
          <!-- 用来显示封面的图片 -->
          <img :src="coverPreview" alt="" class="cover-img" ref="imgRef" />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input
            type="file"
            style="display: none"
            accept="image/*"
            ref="iptFile"
            @change="onCoverChange"
          />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="$refs.iptFile.click()"
            >+ 选择封面</el-button
          >
        </el-form-item>
        <el-button type="primary" @click="pubArticle('已发布')">发布</el-button>
        <el-button type="info" @click="pubArticle('草稿')">存为草稿</el-button>
      </el-form>
    </el-dialog>
    <!-- 查看文章详情的对话框 -->
    <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
      <h1 class="title">{{ detailList.title }}</h1>
      <div class="info">
        <span>作者：{{ detailList.nickname || detailList.username }}</span>
        <span>发布时间：{{ detailList.pub_date }}</span>
        <span>所属分类：{{ detailList.cate_name }}</span>
        <span>状态：{{ detailList.state }}</span>
      </div>
      <!-- 分割线 -->
      <el-divider></el-divider>

      <img
        :src="'http://www.liulongbin.top:3008' + detailList.cover_img"
        alt=""
      />

      <div v-html="detailList.content"></div>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import defaultImg from '@/assets/images/cover.jpg'
export default {
  name: 'ArtList',
  created () {
    this.getListArt()
    this.initArtList()
  },
  data () {
    return {
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      detailVisible: false,
      detailList: [],
      total: 0,
      artList: [],
      coverPreview: defaultImg,
      cateList: [],
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: null,
        state: ''
      },
      pubDialogVisible: false,
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '文章标题的长度为1-30个字符',
            trigger: 'blur'
          }
        ],
        cate_id: [
          { required: true, message: '请选择文章标题', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ],
        cover_img: [{ required: true, message: '请上传图片', trigger: 'blur' }]
      }
    }
  },
  methods: {
    async handleClose (done) {
      const result = await this.$confirm('是否确认删除改文章？', '提示', {
        type: 'warning'
      }).catch((e) => e)
      if (result === 'confirm') {
        return done()
      }
    },
    async getListArt () {
      const { data: res } = await this.$http.get('/my/cate/list')
      if (res.code === 0) {
        this.cateList = res.data
      }
    },
    onCoverChange (e) {
      const files = e.target.files
      if (files.length === 0) {
        this.pubForm.cover_img = ''
        this.coverPreview = defaultImg
      } else {
        this.pubForm.cover_img = files[0]
        const url = URL.createObjectURL(files[0])
        this.coverPreview = url
        this.$refs.pubForm.clearValidate('cover_img')
      }
    },
    pubArticle (state) {
      this.pubForm.state = state
      this.$refs.pubForm.validate(async (result) => {
        if (!result) return
        const fd = new FormData()
        Object.keys(this.pubForm).forEach((k) => fd.append(k, this.pubForm[k]))
        const { data: res } = await this.$http.post('/my/article/add', fd)
        if (res.code === 0) {
          this.pubDialogVisible = false
          this.initArtList()
          // console.log(res)
          // console.log(this.pubForm)
        }
      })
    },
    pubResetClick () {
      this.$refs.pubForm.resetFields()
      this.coverPreview = defaultImg
    },
    async initArtList () {
      const { data: res } = await this.$http.get('/my/article/list', {
        params: this.q
      })
      if (res.code === 0) {
        this.artList = res.data
        this.total = res.total
      }
    },
    forMat (date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    handleSizeChange (size) {
      this.q.pagesize = size
      this.initArtList()
    },
    handleCurrentChange (cur) {
      this.q.pagenum = cur
      this.initArtList()
    },
    resetList () {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.initArtList()
    },
    chooseClick () {
      this.q.pagenum = 1
      this.initArtList()
    },
    async detailClick (id) {
      const { data: res } = await this.$http.get('/my/article/info', {
        params: { id }
      })
      if (res.code === 0) {
        this.detailList = res.data
      }
      this.detailVisible = true
    },
    async delList (id) {
      const result = await this.$confirm(
        '此操作将永久删除该文件，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((e) => e)
      if (result === 'cancel') return
      const { data: res } = await this.$http.delete('/my/article/info', {
        params: { id }
      })
      if (res.code !== 0) return
      if (this.artList.length === 0 && this.q.pagenum > 1) {
        this.q.pagenum--
      }
      this.initArtList()
    }
  }
}
</script>

<style lang="less" scoped>
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}
.el-pagination {
  margin-top: 15px;
}
// 设置富文本编辑器的默认最小高度
/deep/ .ql-editor {
  min-height: 300px;
}
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
</style>
